<template>
  <el-form
    ref="form"
    :inline="formConfig.inline"
    :model="localVal"
    :label-position="formConfig.labelPosition || 'left'"
    :label-width="formConfig.labelWidth || '120px'"
    :size="formConfig.size"
    :status-icon="formConfig.statusIcon"
    :disabled="formConfig.disabled"
    class="dynamic-form"
    :class="{ 'dynamic-form-inline': formConfig.inline }"
    :rules="rules"
  >
    <div v-for="item in formConfig.formItemList" :key="item.key">
      <el-row :gutter="20" v-if="item.type.indexOf('array') > -1">
        <div v-for="index in item.length" :key="index">
          <el-col :span="8" v-if="item.formItemList">
            <h4>{{ `${item.label} - ${index} .` }}</h4>
            <dynamic-form
              style="background-color: #eee"
              v-model="localVal[item.key][index - 1]"
              :form-config="item"
            />
          </el-col>
          <el-col v-else>
            <dynamic-form-item
              :item="{
                ...item,
                type: item.type.split('-')[0],
              }"
              v-if="localVal[item.key]"
              :value="localVal[item.key][index - 1]"
              @input="handleInput($event, item, index - 1)"
            />
          </el-col>
        </div>
      </el-row>
      <el-row v-else-if="item.type === 'object'">
        {{ item.label }}
        <dynamic-form
          style="background-color: #eee"
          v-model="localVal[item.key]"
          :form-config="item"
          @input="handleInput($event, item)"
        />
      </el-row>
      <el-row :gutter="20" v-else>
        <el-col :span="20">
          <dynamic-form-item
            :item="item"
            :value="localVal[item.key]"
            @input="handleInput($event, item)"
          />
        </el-col>
      </el-row>
    </div>
  </el-form>
</template>

<script>
  import DynamicFormItem from './DynamicFormItem';

  export default {
    name: 'DynamicForm',
    components: {
      DynamicFormItem,
    },
    props: {
      formConfig: {
        type: Object,
        required: true,
      },
      value: {
        required: true,
      },
      rules: {
        type: Object,
        required: true,
      },
    },
    data() {
      return {
        localVal: { ...this.value },
      };
    },
    watch: {
      value() {
        this.localVal = { ...this.value };
      },
    },
    mounted() {
      this.setDefaultValue();
    },
    methods: {
      handleInput(val, item, index) {
        // 这里element-ui没有上报event，直接就是value了
        // 数据关联, 可能没人知道我在干嘛,但是这样还是挺厉害的
        if (item.connect) {
          for (const p in item.connect) {
            let res = val[p];
            switch (item.connect[p]) {
              case 'userUrl':
                res = `https://ke.movtile.com/teacher/${res}`;
                break;
            }
            this.$set(this.localVal, item.connect[p], res);
          }
          this.$emit('input', this.localVal);
        } else {
          if (item.type.indexOf('-array') > -1) {
            this.localVal[item.key][index] = val;
            this.$emit('input', { ...this.localVal });
          } else {
            this.$emit('input', { ...this.localVal, [item.key]: val });
          }
        }
      },
      setDefaultValue() {
        const formData = { ...this.value };
        // 设置默认值
        this.formConfig.formItemList.forEach(({ type, key, value }) => {
          if (formData[key] === undefined || formData[key] === null) {
            if (type === 'object') {
              formData[key] = {};
            } else if (type == 'array') {
              formData[key] = [];
            } else {
              formData[key] = value || '';
            }
          }
        });

        this.$emit('input', formData);
      },
      onSubmit() {
        console.log('submit!');
      },
    },
  };
</script>

<style lang="less" scoped>
  .dynamic-form-inline {
    .el-form-item {
      width: 100%;
      /deep/ .el-form-item__content {
        width: 100%;
      }
    }
  }
</style>
